/**
 * @file   MasterLst.java
 * @author Enrique Madrid <e.madrid@lpcsite.com>
 * @date   Mon Sep 24 20:19:52 2007
 * 
 * @brief  
 * 
 * 
 */

package sim.store;

import java.util.Vector;
import java.io.*;
import java.util.*;

import sim.framework.*;
import sim.framework.io.*;
import sim.utils.parser.*;
import sim.utils.*;

public final class MasterLst implements FileGets, ParserScan {

    public static final byte[] FIELD_TOKEN = {':'};
    private static final String MASTER_EMPTY = "";

    private static final int SIZE_INIT_SIZE = 4;
    
    private Simlet m_Simlet;
    
    Hashtable m_Table = new Hashtable(SIZE_INIT_SIZE);
    Parser m_Parser = null;

    private String m_Code =  null;
    private String m_Value = null;
    
    public MasterLst(Simlet s) {
	m_Simlet = s;
	m_Parser = new Parser(this, FIELD_TOKEN, Parser.FORWARD);
    }

    public boolean load(final String filename) {
	FileStream file;
	m_Table.clear();
	file = (FileStream)FileStream.create(m_Simlet, filename, File.MODE_READ);
	if (file != null) {
	    file.gets(this);
	    file.close();
	}
	return (m_Table.size() > 0);
    }

    public boolean fileGetsLine(final byte[] line, int size, int crlf) {
	if (size > crlf) {
	    return m_Parser.scan(line, 0, size - crlf);
	}
	return true;
    }
    
    public boolean parserHit(int hit, final byte[] line, int start, 
			     int length, Object something) {
	switch (hit) {
	case 1:
	    m_Code = Utils.decoding(line, start, length, m_Simlet.getAppEncoding());
	    break;
	case 2:
	    m_Value = Utils.decoding(line, start, length, m_Simlet.getAppEncoding());
	    break;
	}
	return true;
    }
    
    public boolean parserEnd(boolean cancel) {
	if ((m_Code != null) && (m_Value != null)) {
	    m_Table.put(m_Code, m_Value);
	}
	m_Code = null;
	m_Value = null;
	return true;
    }

    public String getString(final String code) {
	String ret;
	ret = (String)m_Table.get(code);
	if (ret != null) {
	    return ret;
	}
	return MASTER_EMPTY;
    }
}
